define(['jquery', 'bootstrap', 'backend', 'table', 'form'], function ($, undefined, Backend, Table, Form) {

    var Controller = {
        out: function () {
            // $('.btn-ajaxshowtrade').data('area',['70%','70%']);
            // $('.btn-outcodeorder').data('area',['70%','70%']);
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'select/order/out' + location.search,
                    //   add_url: 'select/order/add',
                    edit_url: 'select/order/edit',
                    ajaxshowtrade_url: 'select/order/ajaxShowTrade/type=1',
                    importorder_url: 'select/order/importorder',
                    createorder_url: 'select/order/createorder',
                    mergeorder_url: 'select/order/mergeorder',
                    outcodeorder_url: 'select/order/outcodeorder',
                    savenote_url: 'select/order/savenote',
                    savecodeorder_url: 'select/order/savecodeorder',
                    multi_url: 'select/order/multi',
                    import_url: 'select/order/import',
                    table: 'order',
                },
                pageList: [10, 20, 50,100,500]
            });

            var table = $("#table");

            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'o_id',
                sortName: 'o_id',
                fixedColumns: true,
                fixedRightNumber: 1,
                columns: [
                    [
                        {checkbox: true},
                        {field: 'nickname', title: '操作人员', operate: 'LIKE'},
                        {field: 'o_in_uname', title: '客户姓名', operate: 'LIKE'},
                        {field: 'o_order_number', title: __('o_order_number'), operate: 'LIKE'},
                        {field: 'storage_list', title: '数量', operate:false,formatter: function (value){
                                var html = '';
                                $.each(value,function(index,values){
                                    html += values+'<br/>';
                                });
                                return html;}},
                        {field: 'profit_total', title: '订单利润', operate: false},
                        {field: '', title: '已收/应收', operate: false,formatter:function(value,row,index){
                                if(row.order_money_total == row.account_record_money_total){
                                    return '<b>' + row.account_record_money_total+'/'+row.order_money_total+ '</b>'
                                }else{
                                    return '<b style = "color:red">' + row.account_record_money_total+'/'+row.order_money_total+ '</b>'
                                }
                            }
                        },
                        {field: 'account_record_str', title: '转款记录', operate:false,formatter: function (value){
                                var html = '';
                                $.each(value,function(index,values){
                                    html += values+'<br/>';
                                });
                                return html;
                            }},
                        {field: 'o_note', title: __('o_note'), operate: 'LIKE'},
                        {field: 'o_status', title: '状态',searchList: {"-1":"已取消","0":'待出库',"1":'已出库'}, formatter: Table.api.formatter.status },
                        {field: 'o_is_settled', title: '是否清账',searchList: {"0":'未清账',"1":'已结清'}, formatter: Table.api.formatter.status,visible:false },
                        {field: 'order_money_total', title: '订单金额', operate:'BETWEEN'},
                        {field: 'out_storage_list', title: '待出库信息', operate:false,formatter: function (value){
                                var html = '';
                                $.each(value,function(index,values){
                                    html += values+'<br/>';
                                });
                                return html;
                            }},
                        {field: 'o_create_time', title: __('o_create_time'), operate:'RANGE', addclass:'datetimerange', autocomplete:false, formatter: Table.api.formatter.datetime},
                        {field: 'operate', title: __('Operate'), table: table, events: Table.api.events.operate, formatter: Table.api.formatter.operate,
                            buttons: [
                                {
                                    name: 'orderdetail',
                                    text: '收款',
                                    title: '收款',
                                    icon: 'fa',
                                    classname: 'btn btn-xs btn-warning btn-dialog chakan',
                                    extend: 'data-area=\'["70%","70%"]\'',
                                    url: function (row) {
                                        return 'account/record/orderaccountrecord/id/' + row.o_id;
                                    },
                                },
                                {
                                    name: 'orderdetail',
                                    text: '详情',
                                    title: '详情',
                                    icon: 'fa',
                                    classname: 'btn btn-xs btn-warning btn-dialog chakan',
                                    extend: 'data-area=\'["100%","100%"]\'',
                                    url: function (row) {
                                        return 'select/storage/out?oi_order_id=' + row.o_id;
                                    },
                                },
                                {
                                    name: 'savenote',
                                    text: '备注',
                                    title: '备注',
                                    icon: 'fa',
                                    classname: 'btn btn-xs btn-warning btn-dialog chakan',
                                    extend: 'data-area=\'["70%","70%"]\'',
                                    url: function (row) {
                                        return 'select/order/savenote/id/' + row.o_id;
                                    },
                                },
                                {
                                    name: 'orderdetail',
                                    text: '打印出库单',
                                    title: '打印出库单',
                                    icon: 'fa',
                                    classname: 'btn btn-xs btn-warning btn-dialog chakan',
                                    extend: 'data-area=\'["70%","70%"]\'',
                                    url: 'select/order/ajaxShowTrade?type=1',
                                    visible: function (row) {
                                        //返回true时按钮显示,返回false隐藏
                                        return true;
                                    }
                                },
                                {
                                    name: 'callbackmerge', text:'',title:'是否撤回合并' ,  icon: 'fa fa-warning',extend:'data-toggle="tooltip"', classname: 'btn btn-xs btn-ajax btn-primary btn-dialog', url: 'select/order/callbackmerge',
                                    confirm: '是否撤回合并?',
                                    success: function (data, ret) {
                                        $("#table").bootstrapTable('refresh', {});
                                    },
                                    error: function (data, ret) {
                                        console.log(data, ret);
                                        Layer.alert(ret.msg);
                                    },
                                    visible: function (row) {
                                        return true;
                                    },
                                },
                                {
                                    name: 'cancel', text:'取消',title:'是否取消订单' ,  icon: 'fa',extend:'data-toggle="tooltip"', classname: 'btn btn-xs btn-ajax btn-primary btn-dialog', url: 'select/order/cancelOrder',
                                    confirm: '是否取消订单?',
                                    success: function (data, ret) {
                                        $("#table").bootstrapTable('refresh', {});
                                    },
                                    error: function (data, ret) {
                                        console.log(data, ret);
                                        Layer.alert(ret.msg);
                                    },
                                    visible: function (row) {
                                        if(row.o_status != -1){
                                            return true;
                                        }
                                    },
                                },
                            ],
                        }
                    ]
                ],
                onLoadSuccess:function(){
                    // 这里就是数据渲染结束后的回调函数
                    $(".btn-ajaxshowtrade").data("area",["80%","80%"]);
                    $(".btn-outcodeorder").data("area",["80%","80%"]);
                },
            });
            /**
             * 批量弹窗
             */
            $(document).on("click", ".btn-ajaxshowtrade", function (e) {
                // 获取选中的列表ID
                var ids = Table.api.selectedids(table);
                Fast.api.open($.fn.bootstrapTable.defaults.extend.ajaxshowtrade_url + "?ids=" + ids, '打印出库单')
            });


            $(document).on("click", ".btn-createorder", function (e) {
                // 获取选中的列表ID
                Fast.api.open($.fn.bootstrapTable.defaults.extend.createorder_url + "?type=1", '创建订单')
            });

            $(document).on("click", ".btn-outcodeorder", function (e) {
                // 获取选中的列表ID
                Fast.api.open($.fn.bootstrapTable.defaults.extend.outcodeorder_url, '扫码出库')
            });

            $(document).on("click", ".btn-importorder", function (e) {
                // 获取选中的列表ID
                var ids = Table.api.selectedids(table);
                Fast.api.open($.fn.bootstrapTable.defaults.extend.importorder_url+'?type=1', '导入出库订单')
            });

            $(".btn-mergeorder").click(function() {
                var ids = Table.api.selectedids(table)
                //console.log(ids)
                if(ids.length>0)
                    layer.confirm("是否合并订单？", function() {
                        $.ajax({
                            type  : 'post',
                            url: $.fn.bootstrapTable.defaults.extend.mergeorder_url,
                            data: {
                                ids: ids,
                                type:1
                            },
                            success(res) {
                                if (res.code == 1) {
                                    layer.alert("合并成功！")
                                } else {
                                    layer.alert(res.msg)
                                }
                                table.bootstrapTable('refresh', {});
                            }
                        })
                    })
                else{
                    layer.alert("请选择合并订单")
                }
            })

            // table.on('post-body.bs.table',function(){
            //     $(".btn-outcodeorder").data("area",["100%","100%"]);
            // })
            // 为表格绑定事件
            Table.api.bindevent(table);
        },
        incodeorder:function (){
            Template.helper("Fast", Fast);

            //因为日期选择框不会触发change事件，导致无法刷新textarea，所以加上判断
            $(document).on("fa.event.appendfieldlist", "#first-table .btn-append", function (e, obj) {
                // console.log('btn-append====>',obj)
                //绑定动态下拉组件
                // Form.events.selectpage(obj);
                //绑定日期组件
                // Form.events.datetimepicker(obj);
                //绑定上传组件
                // Form.events.faupload(obj);

            });


            // var buffer = ""; // 用于暂存扫码枪输入的文本
            // var timer; // 用于实现延时处理
            let code = ''
            let lastTime, nextTime
            let lastCode, nextCode

            document.addEventListener('keypress', function(e) {
                if (window.event) { // IE
                    nextCode = e.keyCode
                } else if (e.which) { // Netscape/Firefox/Opera
                    nextCode = e.which
                }
                if (e.which === 13 || window.event === 13) {
                    var deviceCode = code;

                    var cate  = $('#c-cate_id').val();
                    //var cate_name=$('#c-cate_id option:selected').text();
                   // var cate_name  = $('#c-cate_id').text();
                    var year  = $('#c-year').val();
                    var specs = $('#c-specs').val();
                    var price = $('#c-price').val();
                    var data ={
                        "oi_code":code,
                        "cate":cate,
                        //"cate_name":cate_name,
                        "oi_year":year,
                        "oi_specs":specs,
                        "oi_date":"",
                        "oi_batch":"",
                        "oi_bottle_code":"",
                        "price":price,
                    };
                    var val = JSON.parse($("textarea[name='row[code_arr]']").val())
                    Form.api.bindevent('form');
                    if(val.length==0){
                        $("textarea[name='row[code_arr]']").val(JSON.stringify([data]));
                        $('.total_num').html(Object.keys([data]).length);
                    }else{
                        $("textarea[name='row[code_arr]']").val(JSON.stringify([...val,data]));
                        $('.total_num').html(Object.keys([...val,data]).length);
                    }
                    $("textarea[name='row[code_arr]']").trigger("fa.event.refreshfieldlist");
                    code = ''
                    lastCode = ''
                    lastTime = ''
                }else{
                    nextTime = new Date().getTime()
                    if (!lastTime && !lastCode) {
                       // console.log('扫码开始。。。')
                        code += e.key
                    }
                    if (lastCode && lastTime && nextTime - lastTime > 500) { // 当扫码前有keypress事件时,防止首字缺失
                       // console.log('防止首字缺失。。。')
                        code = e.key
                    } else if (lastCode && lastTime) {
                       // console.log('扫码中。。。')
                        code += e.key
                    }
                    lastCode = nextCode
                    lastTime = nextTime
                }
            });




            Form.api.bindevent($("form[role=form]"), function (data, ret) {
               Layer.alert(data.data);
            });
        },
        outcodeorder:function (){
            Template.helper("Fast", Fast);

            //因为日期选择框不会触发change事件，导致无法刷新textarea，所以加上判断
            $(document).on("fa.event.appendfieldlist", "#first-table .btn-append", function (e, obj) {
                //绑定动态下拉组件
                Form.events.selectpage(obj);
                //绑定日期组件
                Form.events.datetimepicker(obj);
                //绑定上传组件
                Form.events.faupload(obj);
                $(" .btn-append").hide();
            });


            // var buffer = ""; // 用于暂存扫码枪输入的文本
            // var timer; // 用于实现延时处理
            let code = ''
            let lastTime, nextTime
            let lastCode, nextCode

            // $(document).keypress(function(e) {
            //     // 过滤非字母和数字按键，因为扫码枪通常会产生这些按键
            //     if ((e.which >= 48 && e.which <= 57) || (e.which >= 65 && e.which <= 90)) {
            //         // 是字母数字按键，可能来自键盘
            //     } else {
            //         // 可能来自扫码枪，执行相关操作
            //         console.log('扫码枪输入:', e.which);
            //         // 调用后端处理函数或执行页面跳转等
            //     }
            // });

            document.addEventListener('keypress', function(e) {
                if (window.event) { // IE
                    nextCode = e.keyCode
                } else if (e.which) { // Netscape/Firefox/Opera
                    nextCode = e.which
                }

                if (e.which === 13 || window.event === 13) {
                    var deviceCode = code;
                    $.ajax({
                        'type'  : 'post',
                        'url'   : '/company.php/select/order/selectInfoByCode',
                        'data'  : { code : deviceCode },
                        'dataType'  : 'json',
                        'success'   : function(ret){
                            if(ret.code == 1){
                                var price = $('#c-price').val();
                                var data ={
                                    "oi_code":deviceCode,
                                    "cate":ret.data.cate_id,
                                    "cate_name":ret.data.cate_name,
                                    "oi_year":ret.data.year,
                                    "oi_specs":ret.data.specs,
                                    "oi_date":ret.data.date,
                                    "oi_batch":ret.data.batch,
                                    "oi_bottle_code":ret.data.bottle_code,
                                    "price":price,
                                };
                                var val = JSON.parse($("textarea[name='row[code_arr]']").val())
                                Form.api.bindevent('form');
                                if(val.length==0){
                                    $("textarea[name='row[code_arr]']").val(JSON.stringify([data]));
                                    $('.total_num').html(Object.keys([data]).length);
                                }else{
                                    $("textarea[name='row[code_arr]']").val(JSON.stringify([...val,data]));
                                    $('.total_num').html(Object.keys([...val,data]).length);
                                }
                                $("textarea[name='row[code_arr]']").trigger("fa.event.refreshfieldlist");

                            }else{
                                Layer.alert(ret.msg);
                            }

                        }
                    });
                    code = ''
                    lastCode = ''
                    lastTime = ''
                }else{
                    nextTime = new Date().getTime()
                    if (!lastTime && !lastCode) {
                        //console.log('扫码开始。。。')
                        code += e.key
                    }
                    if (lastCode && lastTime && nextTime - lastTime > 500) { // 当扫码前有keypress事件时,防止首字缺失
                        //console.log('防止首字缺失。。。')
                        code = e.key
                    } else if (lastCode && lastTime) {
                       // console.log('扫码中。。。')
                        code += e.key
                    }
                    lastCode = nextCode
                    lastTime = nextTime
                }

            });




            Form.api.bindevent($("form[role=form]"), function (data, ret) {
                // Layer.alert(data.data);
            });
        },
        refundorder: function () {
            $('.btn-ajaxshowtrade').data('area',['70%','70%']);
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'select/order/refundorder' + location.search,
                    multi_url: 'select/order/multi',

                    table: 'order',
                },
                pageList: [10, 20, 50,100,500]
            });

            var table = $("#table");

            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'o_id',
                sortName: 'o_id',
                fixedColumns: true,
                fixedRightNumber: 1,
                columns: [
                    [
                        {checkbox: true},
                        {field: 'o_in_uname', title: '客户姓名', operate: 'LIKE'},
                        {field: 'o_order_number', title: __('o_order_number'), operate: 'LIKE'},
                        {field: 'storage_list', title: '退库数量', operate:false,formatter: function (value){
                                var html = '';
                                $.each(value,function(index,values){
                                    html += values+'<br/>';
                                });
                                return html;}},
                        {field: 'o_note', title: __('o_note'), operate: 'LIKE'},
                        {field: 'o_status', title: '状态',searchList: {"-1":"已取消","0":'待出库',"1":'已出库'}, formatter: Table.api.formatter.status },
                        {field: 'order_money_total', title: '退库金额', operate:'BETWEEN'},
                        {field: 'o_create_time', title: __('o_create_time'), operate:'RANGE', addclass:'datetimerange', autocomplete:false, formatter: Table.api.formatter.datetime},
                        {field: 'o_refund_time', title: '最新退库时间', operate:'RANGE', addclass:'datetimerange', autocomplete:false, formatter: Table.api.formatter.datetime},
                        {field: 'operate', title: __('Operate'), table: table, events: Table.api.events.operate, formatter: Table.api.formatter.operate,
                            buttons: [
                                {
                                    name: 'orderdetail',
                                    text: '详情',
                                    title: '详情',
                                    icon: 'fa',
                                    classname: 'btn btn-xs btn-warning btn-dialog chakan',
                                    extend: 'data-area=\'["100%","100%"]\'',
                                    url: function (row) {
                                        return 'select/storage/refundinfo?oi_order_id=' + row.o_id;
                                    },
                                },
                            ],
                        }
                    ]
                ]
            });

            // 为表格绑定事件
            Table.api.bindevent(table);
        },
        in: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'select/order/in' + location.search,
                    //   add_url: 'select/order/add',
                    edit_url: 'select/order/edit',
                    ajaxshowtrade_url: 'select/order/ajaxShowTrade/type/2',
                    outwarehouse_url: 'select/order/outwarehouse/type/order',
                    importorder_url: 'select/order/importorder',
                    createorder_url: 'select/order/createorder',
                    incodeorder_url: 'select/order/incodeorder',
                    savenote_url: 'select/order/savenote',
                    del_url: 'select/order/del',
                    multi_url: 'select/order/multi',
                    import_url: 'select/order/import',
                    mergeorder_url: 'select/order/mergeorder',
                    table: 'order',
                },
                pageList: [10, 20, 50,100,500]

            });

            var table = $("#table");

            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'o_id',
                sortName: 'o_id',
                fixedColumns: true,
                fixedRightNumber: 1,
                columns: [
                    [
                        {checkbox: true},
                        {field: 'o_out_uname', title: '供货商姓名', operate: 'LIKE'},
                        {field: 'o_order_number', title: __('o_order_number'), operate: 'LIKE'},
                        {field: 'storage_list', title: '数量', operate:false,formatter: function (value){
                                var html = '';
                                $.each(value,function(index,values){
                                    html += values+'<br/>';
                                });
                                return html;}},
                        {field: '', title: '已付/应付', operate: false,formatter:function(value,row,index){
                                if(row.order_money_total == row.account_record_money_total){
                                    return '<b>' + row.account_record_money_total+'/'+row.order_money_total+ '</b>'
                                }else{
                                    return '<b style = "color:red">' + row.account_record_money_total+'/'+row.order_money_total+ '</b>'
                                }
                            }
                        },
                        {field: 'account_record_str', title: '转款记录', operate:false,formatter: function (value){
                                var html = '';
                                $.each(value,function(index,values){
                                    html += values+'<br/>';
                                });
                                return html;}},
                        {field: 'o_status', title: '状态',searchList: {"0":'待入库',"1":'已入库'}, formatter: Table.api.formatter.status },
                        {field: 'o_is_settled', title: '是否清账',searchList: {"0":'未清账',"1":'已结清'}, formatter: Table.api.formatter.status,visible:false },
                        {field: 'order_money_total', title: '订单金额', operate:'BETWEEN'},
                        {field: 'o_note', title: __('o_note'), operate: 'LIKE'},
                        {field: 'out_storage_list', title: '待入库信息', operate:false,formatter: function (value){
                                var html = '';
                                $.each(value,function(index,values){
                                    html += values+'<br/>';
                                });
                                return html;
                            }},
                        {field: 'o_create_time', title: __('o_create_time'), operate:'RANGE', addclass:'datetimerange', autocomplete:false, formatter: Table.api.formatter.datetime},
                        {field: 'operate', title: __('Operate'), table: table, events: Table.api.events.operate, formatter: Table.api.formatter.operate,
                            buttons: [
                                {
                                    name: 'orderdetail',
                                    text: '付款',
                                    title: '付款',
                                    icon: 'fa',
                                    classname: 'btn btn-xs btn-warning btn-dialog chakan',
                                    extend: 'data-area=\'["70%","70%"]\'',
                                    url: function (row) {
                                        return 'account/record/orderaccountrecord/id/' + row.o_id;
                                    },
                                },
                                {
                                    name: 'orderdetail',
                                    text: '详情',
                                    title: '详情',
                                    icon: 'fa',
                                    classname: 'btn btn-xs btn-warning btn-dialog chakan',
                                    extend: 'data-area=\'["100%","100%"]\'',
                                    url: function (row) {
                                        return 'select/storage/in?oi_order_id=' + row.o_id;
                                    },

                                },
                                {
                                    name: 'savenote',
                                    text: '备注',
                                    title: '备注',
                                    icon: 'fa',
                                    classname: 'btn btn-xs btn-warning btn-dialog chakan',
                                    extend: 'data-area=\'["70%","70%"]\'',
                                    url: function (row) {
                                        return 'select/order/savenote/id/' + row.o_id;
                                    },
                                },

                                {
                                    name: 'orderdetail',
                                    text: '打印入库单',
                                    title: '打印入库单',
                                    icon: 'fa',
                                    classname: 'btn btn-xs btn-warning btn-dialog chakan',
                                    extend: 'data-area=\'["70%","70%"]\'',
                                    url: 'select/order/ajaxShowTrade?type=2',
                                    visible: function (row) {
                                        //返回true时按钮显示,返回false隐藏
                                        return true;
                                    }
                                },
                                {
                                    name: 'callbackmerge', text:'',title:'是否撤回合并' ,  icon: 'fa fa-warning',extend:'data-toggle="tooltip"', classname: 'btn btn-xs btn-ajax btn-primary btn-dialog', url: 'select/order/callbackmerge',
                                    confirm: '是否撤回合并?',
                                    success: function (data, ret) {
                                        $("#table").bootstrapTable('refresh', {});
                                    },
                                    error: function (data, ret) {
                                        console.log(data, ret);
                                        Layer.alert(ret.msg);
                                    },
                                    visible: function (row) {
                                        return true;
                                    },
                                },
                        ],

                        }

                    ]
                ],
                onLoadSuccess:function(){
                    // 这里就是数据渲染结束后的回调函数
                    $(".btn-ajaxshowtrade").data("area",["80%","80%"]);
                    $(".btn-outcodeorder").data("area",["80%","80%"]);
                },
            });


            $(document).on("click", ".btn-createorder", function (e) {
                // 获取选中的列表ID
                var ids = Table.api.selectedids(table);
                Fast.api.open($.fn.bootstrapTable.defaults.extend.createorder_url + "?type=2", '创建订单')
            });
            $(document).on("click", ".btn-incodeorder", function (e) {
                // 获取选中的列表ID
                Fast.api.open($.fn.bootstrapTable.defaults.extend.incodeorder_url, '扫码入库')
            });

            /**
             * 批量弹窗
             */
            $(document).on("click", ".btn-ajaxshowtrade", function (e) {
                // 获取选中的列表ID
                var ids = Table.api.selectedids(table);
                Fast.api.open($.fn.bootstrapTable.defaults.extend.ajaxshowtrade_url + "?ids=" + ids, '打印入库单')
            });
            $(document).on("click", ".btn-outwarehouse", function (e) {
                // 获取选中的列表ID
                var ids = Table.api.selectedids(table);
                Fast.api.open($.fn.bootstrapTable.defaults.extend.outwarehouse_url + "?ids=" + ids, '后台出库')
            });

            $(document).on("click", ".btn-importorder", function (e) {
                // 获取选中的列表ID
                var ids = Table.api.selectedids(table);
                Fast.api.open($.fn.bootstrapTable.defaults.extend.importorder_url+'?type=2', '导入入库订单')
            });

            $(".btn-mergeorder").click(function() {
                var ids = Table.api.selectedids(table)
                //console.log(ids)
                if(ids.length>0)
                    layer.confirm("是否合并订单？", function() {
                        $.ajax({
                            type  : 'post',
                            url: $.fn.bootstrapTable.defaults.extend.mergeorder_url,
                            data: {
                                ids: ids,
                                type:2
                            },
                            success(res) {
                                if (res.code == 1) {
                                    layer.alert("合并成功！")
                                } else {
                                    layer.alert(res.msg)
                                }
                                table.bootstrapTable('refresh', {});
                            }
                        })
                    })
                else{
                    layer.alert("请选择合并订单")
                }
            })

            // 为表格绑定事件
            Table.api.bindevent(table);
        },
        redeposit: function () {
            Controller.api.bindevent();
        },
        createorder: function () {
            Controller.api.bindevent();

            //添加规格
            $('#addskus').on('click', function () {
                var year = $('#space_year').val();
                //  var customer = $('#space_customer').text();
                var category_id = $('#space_category').val();
                //var category_name = $('#space_category').val();
                var spec = $('#space_spec').val();
                var price = $('#space_price').val();
                var num = $('#space_num').val();
                // console.log(customer_id);
                if (!category_id || !spec || !price || !num) {
                    layer.msg('请完善信息');
                    return false;
                }



                $.ajax({
                    url: "select/category/detail",
                    type: 'post',
                    dataType: 'json',
                    data: {id: category_id},
                    success: function (ret) {
                        var category_name = ret.data.c_title;
                        if (category_name == '') {
                            layer.msg('分类信息未查到');
                            return false;
                        } else {
                            var object = new Object();
                            //  object.id = id;
                            object.year = year;
                            object.category_id = category_id;
                            object.spec = spec;
                            object.price = price;
                            object.num = num;
                            var spacenamelist = $('#c-relation').val();
                            if (spacenamelist == '') {
                                //首次添加
                                spacenamelist = new Array();
                                spacenamelist.push(object);
                                spacenamelist = JSON.stringify(spacenamelist);
                            } else {
                                spacenamelist = JSON.parse(spacenamelist);
                                spacenamelist.push(object);
                                spacenamelist = JSON.stringify(spacenamelist);
                            }
                            $('#c-relation').val(spacenamelist);


                            var space_list = '<div class="form-group skuMain">' +
                                '<label class="control-label col-xs-1 col-sm-1" style="width: 7%">' + year + '</label>' +
                                ' <div class="control-label col-xs-1 col-sm-1" style="width: 10%">'+category_name+'</div> ' +
                                ' <div class="control-label col-xs-1 col-sm-1" >'+spec+'</div> ' +
                                ' <div class="control-label col-xs-1 col-sm-1" >'+price+'</div> ' +
                                ' <div class="control-label col-xs-1 col-sm-1" style="width: 7%">'+num+'</div> ' +
                                '<div class="col-xs-3 col-sm-3"> <span class="btn btn-danger" >移除</span></div> ' +
                                '<div class="col-xs-8 col-sm-8 col-xs-offset-2 col-sm-offset-2 skuChildrenBox"></div>' +
                                '</div>';
                            $('#space').append(space_list);
                        }
                    }, error: function (e) {
                        Backend.api.toastr.error(e.message);
                    }
                });



            });

            //移除规格
            $('#space').on('click', '.btn-danger', function (e) {
                //获取规格名称
                var text = $($(this).parent().parent().children()[0]).text();
                text = text.substring(0, text.length - 1)
                //删除规格值
                var spacenamelist = $('#c-relation').val();
                spacenamelist = JSON.parse(spacenamelist);
                for (var i = 0; i < spacenamelist.length; i++) {
                    if (spacenamelist[i]['customer'] == text) {
                        spacenamelist.splice(i, 1);
                    }
                }
                $('#c-relation').val(JSON.stringify(spacenamelist));
                $(this).parent().parent().remove();
                //删除skus_value skus_title
                $('#skus_value').html('');
                $('#skus_title').html('');
            });
        },
        add: function () {
            Controller.api.bindevent();
        },
        edit: function () {
            Controller.api.bindevent();
        },
        outwarehouse: function () {
            Controller.api.bindevent();
        },
        mergeorder: function () {
            Controller.api.bindevent();
        },
        importorder: function () {
            Controller.api.bindevent();
        },
        savenote: function () {
            Controller.api.bindevent();
        },
        ajaxshowtrade: function () {
            Controller.api.bindevent();
            //添加规格
            $(document).on("click", ".print", function(){
                window.print();
            });
        },

        api: {
            bindevent: function () {
                Form.api.bindevent($("form[role=form]"));

            }

        }
    };
    return Controller;
});
